﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using SiteProjects.My_Tasks;
using SiteProjects.Classes;
using Microsoft.SharePoint.Administration;
using System.ComponentModel;

/*
Developed By: Sujeet Kumer
Developed On: 11th Feb 2010
Description: The code provides User,s all the tasks  assign on all the projects on RIC.   
*/

namespace SiteProjects.My_Tasks
{
    public partial class My_TasksUserControl : UserControl
    {
       // TaskLibrary objTasksLib = new TaskLibrary();
       
        SPUser user;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                BindAllProjectTasks();
            }
            catch { }

        }

        /// <summary>
        /// This data bound used to bind the ShowAssignedTasks datagrid to show data.
        /// </summary>
        /// <param></param> 
        /// <returns></returns>
        protected void BindAllProjectTasks()
        {
            DataSet dsTasks = new DataSet();
            DataTable dtAssignTasks = new DataTable();
            dsTasks = GetProjectDetail();

            if (dsTasks.Tables[0].Rows.Count == 0)
            {
                lblmessage.Text = "There are no items to show in this view.";
                lblmessage.Visible = true;
            }
            else
            {
                dtAssignTasks = BindTasksTable(dsTasks);
                if (dtAssignTasks.Rows.Count == 0)
                {
                    lblmessage.Text = "There are no items to show in this view.";
                    lblmessage.Visible = true;
                }
                gvShowAllAssignTask.DataSource = dtAssignTasks;
                gvShowAllAssignTask.DataBind();
            }

        }

       
        /// Fetch and Populate all the Assign Task For current user from all Project site.
        /// </summary>
        /// <param name="dsAssignedTask"></param> 
        /// <returns>DataTable</returns>
        protected DataTable BindTasksTable(DataSet dsAssignedTask)
        {
            DataTable dtTasks = new DataTable();
            dtTasks.Columns.Add("TaskURL", typeof(String));
            dtTasks.Columns.Add("Project", typeof(String));
            dtTasks.Columns.Add("Title", typeof(String));
            dtTasks.Columns.Add("AssignedTo", typeof(String));
            dtTasks.Columns.Add("CreatedBy", typeof(String));
            SPSite webSite = SPContext.Current.Site;
            string projectUrl, taskurl, projectRUrl = string.Empty;
            string projectTitle = string.Empty;
            bool chkListExists;
            for (int icount = 0; icount < dsAssignedTask.Tables[0].Rows.Count; icount++)
            {
                // projecturl = webSite.Url  + "/" + ds.Tables[0].Rows[icount]["FullUrl"].ToString();

                string[] url = webSite.Url.Split('/');
                // projectUrl = url[0] + "//" + url[2] + "/" + dsAssignedTask.Tables[0].Rows[icount]["FullUrl"].ToString();
                projectTitle = dsAssignedTask.Tables[0].Rows[icount]["ProjectTitle"].ToString();
                projectRUrl = dsAssignedTask.Tables[0].Rows[icount]["ProjectRUrl"].ToString();
                projectUrl = dsAssignedTask.Tables[0].Rows[icount]["ProjectUrl"].ToString();
                taskurl = projectRUrl + "/" + "/Lists/Tasks/DispForm.aspx?ID=";
            
                using (SPSite site = new SPSite(projectUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        chkListExists = SharepointManager.ListExists(web, "Tasks");

                        if (chkListExists)
                        {
                            SPList list = web.Lists["Tasks"];
                            SPListItemCollection itemColl;
                            SPQuery query = new SPQuery();
                            query.Query =
                                "<Where>" +
                                "<Contains><FieldRef Name=\"AssignedTo\"/><Value Type=\"Integer\"><UserID Type=\"Integer\" /> </Value></Contains>" +
                                "</Where>";

                            itemColl = list.GetItems(query);

                            if (itemColl.Count > 0)
                            {
                                for (int icntTasks = 0; icntTasks < itemColl.Count; icntTasks++)
                                {
                                    SPListItem listItem = itemColl[icntTasks];
                                    DataRow drow = dtTasks.NewRow();
                                    drow["TaskURL"] = taskurl + listItem["ID"].ToString();
                                    drow["Project"] = projectTitle;
                                    drow["Title"] = listItem["Title"].ToString();
                                    drow["AssignedTo"] = listItem["Assigned To"].ToString();
                                    SPFieldUserValue userValue = new SPFieldUserValue(listItem.Web, listItem["Created By"] as string);
                                    drow["CreatedBy"] = userValue.User.Name;
                                    dtTasks.Rows.Add(drow);
                                }

                            }

                        }

                    }

                }

            }

            return dtTasks;

        }


        /// <summary>
        /// This data bound used to get the text and url
        /// </summary>
        /// <param name="dsAssignedTask"></param> 
        /// <returns></returns>
        protected void gvShowAllAssignTask_ItemDataBound(object sender, DataGridItemEventArgs e)
        {

        }


        protected void gvShowAllAssignTask_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvShowAllAssignTask.PageIndex = e.NewPageIndex;
            gvShowAllAssignTask.DataBind();
        }

        /// <summary>
        /// This dateset return all the projects in witch current user is enroled.
        /// </summary>
        /// <param name="dsAssignedTask"></param> 
        /// <returns></returns>
        protected DataSet GetProjectDetail()
        {
            user = SPContext.Current.Web.CurrentUser;
            DataSet dsProjectDetail = new DataSet();
            DataTable dtProjectDetail = new DataTable();

            dtProjectDetail.Columns.Add("ProjectTitle", typeof(String));
            dtProjectDetail.Columns.Add("ProjectRUrl", typeof(String));
            dtProjectDetail.Columns.Add("ProjectUrl", typeof(String));
            SPWebApplication webApplication = SPContext.Current.Site.WebApplication;
            SPSiteCollection siteCollections = webApplication.Sites;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                foreach (SPSite siteCollection in siteCollections)
                {
                    foreach (SPWeb web in siteCollection.AllWebs)
                    {
                         
                        if (web.DoesUserHavePermissions(user.LoginName, SPBasePermissions.ViewPages) && siteCollection.Url.IndexOf("/projects/") > 1)
                        {
                            DataRow row = dtProjectDetail.NewRow();
                            row["ProjectTitle"] = web.Title;
                            row["ProjectRUrl"] = web.ServerRelativeUrl;
                            row["ProjectUrl"] = web.Url;
                            dtProjectDetail.Rows.Add(row);
                        }
                        web.Dispose();
                       
                    }
                }
            });
            dsProjectDetail.Tables.Add(dtProjectDetail);
            return dsProjectDetail;
           
        }
    }
}

